package com.sc.nft.admin.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.sc.nft.admin.util.qywx.AesException;
import com.sc.nft.admin.util.qywx.WXBizJsonMsgCrypt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
@RequiredArgsConstructor
public class QywxConfig {

    @Value("${qywx.token}")
    public String token;
    @Value("${qywx.secret}")
    public String secret ;
    @Value("${qywx.EncodingAESKey}")
    public String EncodingAESKey ;
    @Value("${qywx.qyWxId}")
    public String qyWxId ;
    @Value("${qywx.agentid}")
    public Integer agentid;

    private final RedisTemplate redisTemplate;

    @Bean
    public WXBizJsonMsgCrypt initCrypt() throws AesException {
        return new WXBizJsonMsgCrypt(token, EncodingAESKey, qyWxId);
    }

    public String getWeChatToken() {
        //如果accessToken存在redis中，通过redis获取 否则重新获取
        Object token =  redisTemplate.opsForValue().get("accessToken");
        if (ObjectUtil.isNotNull(token)) {
            return (String)token;
        }
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + qyWxId + "&corpsecret=" + secret;
        String s = HttpUtil.get(url);
        log.info("accessToken result {}",s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.get("access_token").toString();
        redisTemplate.opsForValue().set(accessToken, accessToken, 7100, TimeUnit.SECONDS);
        return accessToken;
    }

}
